package com.hxs.hxsserver.utils;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class EmailSender {
    public static void EmailSender(String email,String msg) {
        // 邮件发送者和接收者的信息
        final String senderEmail = "edaworks@163.com"; //
        final String senderPassword = "YESvZ9GJmLq7neFX"; // 替换为你的邮箱密码或授权码  RCTKQWhwmEhJmjZy
        final String recipientEmail = email; //

        // 配置 163 邮箱 SMTP
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com");      // 163 SMTP 服务器
        props.put("mail.smtp.port", "465");               // SMTP 端口号
        props.put("mail.smtp.auth", "true");              // 启用身份验证
        props.put("mail.smtp.ssl.enable", "true");        // 启用 SSL 加密

        // 创建会话对象
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        });

        try {
            // 创建邮件内容
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));        // 发件人
            message.setRecipients(Message.RecipientType.TO,          // 收件人
                    InternetAddress.parse(recipientEmail));
            message.setSubject("预警邮件");                            // 邮件标题
            message.setText(msg); // 邮件正文

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功！");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败！");
        }
    }
}
